package no.nordicsemi.android.dfuupdate;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.gson.Gson;

import java.util.HashMap;

import no.nordicsemi.android.dfuupdate.bean.PutTag;
import no.nordicsemi.android.dfuupdate.bean.UpdateTag;
import no.nordicsemi.android.dfuupdate.dfu.TagListActivity;
import no.nordicsemi.android.dfuupdate.scanner.ScanActivity;
import no.nordicsemi.android.dfuupdate.scanner.ScanAutoActivity;
import no.nordicsemi.android.dfuupdate.scanner.ScanBatchActivity;
import no.nordicsemi.android.dfuupdate.server.TaskService;
import no.nordicsemi.android.dfuupdate.utility.DeviceIdUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    //初始化框架 AlertDialog.Builder setTitle与Retrofit.Builder比较前者快速创建对话后者快速初始化retrofit框架
    private String baseUrl="http://103.229.214.118:8099/";//retrofit要求以/结束,否则会产生错误
    private TextView text;
    private String uuid;
    private int update_id = 0;
    private double update_swver = 1.0;
    private int status = 1;
    int i = 1;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        public void run() {
            this.update();
          //  handler.postDelayed(this, 1000 * 2);// 间隔120秒
        }
        void update() {
            //刷新msg的内容
           // i++;
         //   msg.setText("你好啊！"+i);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitivity_main);
        final Toolbar toolbar  = findViewById(R.id.toolbar_actionbar);
        setSupportActionBar(toolbar);
        String testData = getFilterMac("FA:E6:DA:85:3A:19");
        Log.d("Main#####",testData);

        init();
        uuid = DeviceIdUtil.getIMEIDeviceId(getApplicationContext());
        Log.d("uuid =",uuid);
        text = new TextView(MainActivity.this);
       // handler.postDelayed(runnable, 1000 * 3);
       //  putTag(update_id,update_swver,uuid,status);
    }

    public void init () {
        findViewById(R.id.ble_scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ////////////////////////
                // direct to ble scan acitivity
                ////////////////////////
                final Intent intent = new Intent(MainActivity.this, ScanActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.ble_auto_scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取需要升级标签
               // getUpdateTag(update_id,update_swver,uuid);
                final Intent intent = new Intent(MainActivity.this,
                        ScanAutoActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.ble_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ////////////////////////
                // direct to ble search activity
                ////////////////////////
                final Intent intent = new Intent(MainActivity.this,
                        ScanBatchActivity.class);
                startActivity(intent);

                //********************
                // ** start from here test the continually connect multiple device one by one
                //********************
//                final Intent intent_1 = new Intent(MainActivity.this, ReqActivity.class);
//                startActivity(intent_1);

            }
        });

        findViewById(R.id.tag_state).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //查看标签状态
                // getUpdateTag(update_id,update_swver,uuid);
                final Intent intent = new Intent(MainActivity.this,
                        TagListActivity.class);
                startActivity(intent);
            }
        });
    }

    private String getFilterMac(String mac){
        String newMac = "";
        if(!TextUtils.isEmpty(mac)){
            newMac = mac.replaceAll(":","").trim();
        }
        return newMac;
    }
    /*
    * 获取需要升级标签
    * */

    private void getUpdateTag(int id ,double swver,String uuid){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)//设置项目路径 其它路径都改成相对路径 与ApiUrls   HOST    HOME=HOST+"/home"/
                .addConverterFactory(GsonConverterFactory.create(new Gson()))//convert就是将json解析成javaBean
                .build();//执行创建方法

        //调用retrofit框架去读到一个请求需要的全部参数,参数都是注解或者泛型来标注
        TaskService taskService = retrofit.create(TaskService.class);//读取请求方式 请求页面 返回参数

        HashMap<String, Object> params=new HashMap<>();
        params.put("id",id);
        params.put("swver",swver);
        params.put("uuid",uuid);
        Call<UpdateTag> method = taskService.getTag(params);

        //执行子线程，处理服务端返回数据 都是将数据传给回调对象(空方法，给开发者编写业务逻辑，注意条件)
        Callback<UpdateTag> callback=new Callback<UpdateTag>() {
            //处理请求成功的业务逻辑
            @Override
            public void onResponse(Call<UpdateTag> call, Response<UpdateTag> response) {
                //从响应里面获取解析后的javaBean
                UpdateTag data = response.body();
                Log.i("data===",data.getData().getMacId());
                if (data != null) {
                    update_id = data.getData().getId();
                    update_swver = data.getData().getSwver();
                }
            }
            //处理请求失败的业务逻辑
            @Override
            public void onFailure(Call<UpdateTag> call, Throwable t) {
                t.printStackTrace();
                text.setText(t.getMessage());
            }
        };
        method.enqueue(callback);
    }


    /*
     * 上传升级标签状态
     * */

    private void putTag(int id ,double swver,String uuid,int status){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)//设置项目路径 其它路径都改成相对路径 与ApiUrls   HOST    HOME=HOST+"/home"/
                .addConverterFactory(GsonConverterFactory.create(new Gson()))//convert就是将json解析成javaBean
                .build();//执行创建方法

        //调用retrofit框架去读到一个请求需要的全部参数,参数都是注解或者泛型来标注
        TaskService taskService = retrofit.create(TaskService.class);//读取请求方式 请求页面 返回参数

        HashMap<String, Object> params=new HashMap<>();
        params.put("id",id);
        params.put("swver",swver);
        params.put("uuid",uuid);
        params.put("status",status);
        Call<PutTag> method = taskService.putTag(params);

        //执行子线程，处理服务端返回数据 都是将数据传给回调对象(空方法，给开发者编写业务逻辑，注意条件)
        Callback<PutTag> callback=new Callback<PutTag>() {
            //处理请求成功的业务逻辑
            @Override
            public void onResponse(Call<PutTag> call, Response<PutTag> response) {
                //从响应里面获取解析后的javaBean
                PutTag data = response.body();
                Log.i("data===",data.getMsg()+"   "+data.getStat());
                if (data != null &&data.getStat().equals("SUCCESS")) {
                    update_id = data.getData().getId();
                    update_swver = data.getData().getSwver();
                }
            }
            //处理请求失败的业务逻辑
            @Override
            public void onFailure(Call<PutTag> call, Throwable t) {
                t.printStackTrace();
                text.setText(t.getMessage());
            }
        };
        method.enqueue(callback);
    }


    @Override
    protected void onDestroy() {
        handler.removeCallbacks(runnable); //停止刷新
        super.onDestroy();
    }
}
